package org.jeecg.modules.hc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.hc.entity.*;
import org.jeecg.modules.hc.enums.*;
import org.jeecg.modules.hc.mapper.*;
import org.jeecg.modules.hc.service.*;
import org.jeecg.modules.hc.service.impl.pojo.AddressPojo;
import org.jeecg.modules.hc.utils.HcUtils;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.Collator;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @Description: 商家订单
 * @Author: jeecg-boot
 * @Date: 2022-12-20
 * @Version: V1.0
 */
@Service
@Slf4j
public class HcOrderMerchantServiceImpl extends ServiceImpl<HcOrderMerchantMapper, HcOrderMerchant> implements IHcOrderMerchantService {

    @Resource
    private HcOrderMerchantMapper hcOrderMerchantMapper;

    @Resource
    private IHcSystemConfService hcSystemConfService;

    @Autowired
    private IHcMerchantService hcMerchantService;

    @Autowired
    private IHcCommodityService hcCommodityService;

    @Autowired
    private IHcAfterSalesService hcAfterSalesService;

    @Autowired
    private IHcOrderDetailedService hcOrderDetailedService;

    @Lazy
    @Autowired
    private IHcOrderService hcOrderService;

    @Autowired
    private IHcWalletService hcWalletService;

    @Autowired
    private IHcSiteAddressDetailsService hcSiteAddressDetailsService;

    @Autowired
    private IHcWxPayService hcWxPayService;

    @Autowired
    private IHcWxPayRefundService hcWxPayRefundService;

    @Autowired
    private IHcAliPayService hcAliPayService;

    @Autowired
    private IHcAliRefundService hcAliRefundService;

    @Autowired
    private IHcMerchantSettlementService hcMerchantSettlementService;

    @Resource
    private HcCompanyMerchantInfoMapper hcCompanyMerchantInfoMapper;

    @Resource
    private HcCompanyInfoMapper hcCompanyInfoMapper;


    @Resource
    private HcCompanyFoodOrderMapper hcCompanyFoodOrderMapper;

    @Resource
    private HcCompanyPickupAddressMapper hcCompanyPickupAddressMapper;
    @Resource
    private HcCompanyMerchantSettingMapper hcCompanyMerchantSettingMapper;
    @Autowired
    private IHcCompanyPickupAddressService hcCompanyPickupAddressService;



    @Value("${jeecg.path.upload}")
    private String upLoadPath;


    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;



    public JSONObject queryGlobalData(JSONObject param) {
        JSONObject result = new JSONObject();
        String date = param.getString("date");

        JSONObject yongShanTuanTime = HcUtils.getYongShanTuanTime(date);
        param.put("beginTime", yongShanTuanTime.getString("beginTime"));
        param.put("endTime", yongShanTuanTime.getString("endTime"));

        List<Map> globalData1 = hcOrderMerchantMapper.queryGlobalData1(param);
        List<Map> globalData2 = hcOrderMerchantMapper.queryGlobalData2(param);
        result.put("globalData1", globalData1);
        result.put("globalData2", globalData2);
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<?> importExcelByMaiKe(HttpServletRequest request) {
        long start = System.currentTimeMillis();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setHeadRows(1);
            params.setSheetNum(1);
            params.setNeedSave(true);
            try {
                List<HcOrderMerchant> list = ExcelImportUtil.importExcel(file.getInputStream(), HcOrderMerchant.class, params);
                int i = 1;
                for (HcOrderMerchant hcOrderMerchant : list) {
                    if (StringUtils.isBlank(hcOrderMerchant.getSupplyAddress()) &&
                            StringUtils.isBlank(hcOrderMerchant.getStoreName()) &&
                            StringUtils.isBlank(hcOrderMerchant.getNameDishes()) &&
                            hcOrderMerchant.getTotalPrice() == null
                    ) {
                        continue;
                    }

                    if (StringUtils.isBlank(hcOrderMerchant.getSupplyAddress()) ||
                            StringUtils.isBlank(hcOrderMerchant.getStoreName()) ||
                            StringUtils.isBlank(hcOrderMerchant.getNameDishes()) ||
                            hcOrderMerchant.getTotalPrice() == null
                    ) {
                        throw new JeecgBootException("第" + i + "行数据错误请检查，地址，门店名称，菜品名称，消费金额必填");
                    }

                    String storeName = hcOrderMerchant.getStoreName();
                    HcMerchant hcMerchant = null;

                    try {
                        hcMerchant = hcMerchantService.getOne(new LambdaQueryWrapper<HcMerchant>().eq(HcMerchant::getStoreName, storeName));
                    } catch (Exception e) {
                        log.error("门店查询错误, 门店名称：{}", storeName);
                        throw new JeecgBootException("门店查询错误");
                    }

                    if (hcMerchant == null) {
                        throw new JeecgBootException(storeName + " 门店不在系统中");
                    }

                    String nameDishes = hcOrderMerchant.getNameDishes();
                    String tradeName = "";
                    Integer commodityQuantity = 1;
                    HcCommodity hcCommodity = null;

                    try {
                        if (nameDishes.contains("*")) {
                            String[] split = nameDishes.split("\\*");
                            tradeName = split[0];
                            commodityQuantity = Integer.valueOf(split[1]);
                        } else {
                            tradeName = nameDishes;
                        }
                    } catch (Exception e) {
                        log.error("菜品名称解析失败：{}", nameDishes);
                        throw new JeecgBootException("菜品名称解析失败: " + nameDishes);
                    }

                    try {
                        hcCommodity = hcCommodityService.getOne(new LambdaQueryWrapper<HcCommodity>()
                                .eq(HcCommodity::getTradeName, tradeName)
                                .eq(HcCommodity::getMerchantId, hcMerchant.getId())
                                .last(" limit 1 ")
                        );
                    } catch (Exception e) {
                        log.error("菜品查询错误, 菜品名称：{}", tradeName);
                        throw new JeecgBootException("菜品查询错误: " + tradeName);
                    }

                    if (hcCommodity == null) {
                        throw new JeecgBootException(tradeName + " 菜品不在系统中或者不属于 " + storeName + " 门店");
                    }

                    Map map = getAddressIdByCode(hcOrderMerchant.getSupplyAddress());
                    AtomicReference<String> siteId = (AtomicReference<String>)map.get("siteId");
                    String pickAddress = (String) map.get("pickAddress");
                    System.out.println(pickAddress);
                    System.out.println(siteId);
                    if (StringUtils.isBlank(siteId.get())){
                        throw new JeecgBootException("第" + i + "行数据错误请检查，地址，门店名称，菜品名称，消费金额必填");
                    }

                    HcOrderMerchant save = new HcOrderMerchant();
                    save.setImportFlag(HcIsFlagEnum.YES);
                    save.setUserId("");
                    save.setOrderId("");
                    save.setState(HcOrderStateEnum.PAY);
                    save.setNameTakingMeal(hcOrderMerchant.getNameTakingMeal() == null ? "" : hcOrderMerchant.getNameTakingMeal());
                    save.setPhoneTakingMeals(hcOrderMerchant.getPhoneTakingMeals() == null ? "" : hcOrderMerchant.getPhoneTakingMeals());
                    save.setPickingAddress(pickAddress);
                    save.setSupplyAddress(hcOrderMerchant.getSupplyAddress());
                    save.setAddressId(siteId.get());
                    save.setRemarks(hcOrderMerchant.getRemarks());

                    save.setMerchantId(hcMerchant.getId());
                    save.setStoreDescription(hcMerchant.getStoreDescription());
                    save.setStoreName(hcMerchant.getStoreName());
                    save.setLogo(hcMerchant.getLogo());
                    save.setPickingSerialNo(hcOrderMerchant.getPickingSerialNo());
                    save.setCreateBy("admin");
                    save.setCreateTime(new Date());

                    log.info("菜品信息：{}", JSON.toJSONString(hcCommodity));

                    BigDecimal multiply = hcCommodity.getCommodityPrice().multiply(new BigDecimal(commodityQuantity));

                    if (hcOrderMerchant.getTotalPrice().compareTo(multiply) < 0) {
                        throw new JeecgBootException("第" + i + "行数据消费金额小于系统的合作单价，请修改后重新导入");
                    }

                    save.setTotalPrice(hcOrderMerchant.getTotalPrice());
                    save.setCommodityPrice(multiply);
                    save.setCommission(hcOrderMerchant.getTotalPrice().subtract(multiply));
                    save.setUpdateTime(new Date());
                    this.save(save);

                    HcOrderDetailed hcOrderDetailed = new HcOrderDetailed();
                    hcOrderDetailed.setOrderId("");
                    hcOrderDetailed.setOrderMerchantId(save.getId());

                    hcOrderDetailed.setCommodityId(hcCommodity.getId());
                    hcOrderDetailed.setCommodityQuantity(commodityQuantity);
                    hcOrderDetailed.setCommodityPrice(hcOrderMerchant.getTotalPrice());
                    hcOrderDetailed.setTradeName(hcCommodity.getTradeName());
                    hcOrderDetailed.setProductPicture(hcCommodity.getProductPicture());
                    hcOrderDetailed.setCommission(hcOrderMerchant.getTotalPrice().subtract(multiply));
                    hcOrderDetailed.setCreateBy("admin");
                    hcOrderDetailed.setCreateTime(new Date());
                    hcOrderDetailedService.save(hcOrderDetailed);

                    i++;
                }

                //update-begin-author:taoyan date:20190528 for:批量插入数据
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                //update-begin-author:taoyan date:20211124 for: 导入数据重复增加提示
                String msg = e.getMessage();
                log.error(msg, e);
                if (msg != null && msg.indexOf("Duplicate entry") >= 0) {
                    throw new JeecgBootException("文件导入失败:有重复数据！");
                } else {
                    throw new JeecgBootException("文件导入失败:" + e.getMessage());
                }
                //update-end-author:taoyan date:20211124 for: 导入数据重复增加提示
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    @Override
    public IPage<HcOrderMerchant> getOrderListByMerchantId(Page<HcOrderMerchant> page, HcOrderMerchant param) {
        return hcOrderMerchantMapper.getOrderListByMerchantId(page, param);
    }

    @Override
    public List<Map> getStatisticsList(Map param) {
        return hcOrderMerchantMapper.getStatisticsList(param);
    }

    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(String id) throws WxPayException, AlipayApiException {
        HcOrderMerchant hcOrderMerchant = this.getById(id);

        if (hcOrderMerchant.getImportFlag().equals(HcIsFlagEnum.YES)) {
            this.updateById(new HcOrderMerchant().setId(hcOrderMerchant.getId()).setState(HcOrderStateEnum.CANCELED));
            return;
        }

        if (hcOrderMerchant.getState().equals(HcOrderStateEnum.CANCELED) || hcOrderMerchant.getState().equals(HcOrderStateEnum.REFUNDING)) {
            throw new JeecgBootException("已取消或退款中，请勿重复点击");
        }

        HcOrder hcOrder = hcOrderService.getById(hcOrderMerchant.getOrderId());

        if (hcOrder.getPaymentMethod().equals(HcPaymentMethodEnum.WALLET)) {
            //处理钱包退款
            HcWallet wallet = new HcWallet().setUserId(hcOrderMerchant.getUserId()).setSource(HcWalletSourceEnum.REFUND).setAmount(hcOrderMerchant.getTotalPrice()).setRelationId(hcOrderMerchant.getId());

            hcWalletService.save(wallet);
            this.updateById(new HcOrderMerchant().setId(hcOrderMerchant.getId()).setState(HcOrderStateEnum.CANCELED).setRefundWalletId(wallet.getId()));
        } else if (hcOrder.getPaymentMethod().equals(HcPaymentMethodEnum.WXPAY) || hcOrder.getPaymentMethod().equals(HcPaymentMethodEnum.WALLET_WXPAY) || hcOrder.getPaymentMethod().equals(HcPaymentMethodEnum.PC_WX)) {
            HcWxPay hcWxPay = hcWxPayService.getById(hcOrder.getPaymentId());

            if (hcOrder.getPaymentMethod().equals(HcPaymentMethodEnum.WXPAY) || hcOrder.getPaymentMethod().equals(HcPaymentMethodEnum.PC_WX)) {
                //处理微信退款
                HcWxPayRefund refund = hcWxPayRefundService.refund(hcWxPay.getOutTradeNo(), hcOrder.getUserId(), hcWxPay.getAmountTotal(), hcOrderMerchant.getTotalPrice());
                this.updateById(new HcOrderMerchant().setId(hcOrderMerchant.getId()).setState(HcOrderStateEnum.REFUNDING).setRefundId(refund.getId()));
            } else if (hcOrder.getPaymentMethod().equals(HcPaymentMethodEnum.WALLET_WXPAY)) {
                //获取当前订单下已退款的数据
                List<HcOrderMerchant> hcOrderMerchantList = this.list(new LambdaQueryWrapper<HcOrderMerchant>().eq(HcOrderMerchant::getOrderId, hcOrder.getId()).in(HcOrderMerchant::getState, HcOrderStateEnum.CANCELED, HcOrderStateEnum.REFUNDING));

                Integer refund = hcOrderMerchant.getTotalPrice().multiply(new BigDecimal("100")).intValue();
                Integer refundTotal = 0;
                System.out.println("============= 需要退款的金额 分：" + refund);
                if (!CollectionUtils.isEmpty(hcOrderMerchantList)) {
                    for (HcOrderMerchant orderMerchant : hcOrderMerchantList) {
                        if (StringUtils.isNotBlank(orderMerchant.getRefundId())) {
                            HcWxPayRefund payRefund = hcWxPayRefundService.getById(orderMerchant.getRefundId());
                            refund += payRefund.getRefund();
                            refundTotal += payRefund.getRefund();
                        }

                        if (StringUtils.isNotBlank(orderMerchant.getRefundWalletId())) {
                            HcWallet wallet = hcWalletService.getById(orderMerchant.getRefundWalletId());
                            refund += wallet.getAmount().multiply(new BigDecimal("100")).intValue();
                        }
                    }
                }
                System.out.println("============= 总退款的金额 分：" + refund);
                //如果付款金额大于总退款金额 则直接调用微信退款
                if (hcWxPay.getAmountTotal() >= refund) {
                    HcWxPayRefund hcWxPayRefund = hcWxPayRefundService.refund(hcWxPay.getOutTradeNo(), hcOrder.getUserId(), hcWxPay.getAmountTotal(), hcOrderMerchant.getTotalPrice());
                    this.updateById(new HcOrderMerchant().setId(hcOrderMerchant.getId()).setState(HcOrderStateEnum.REFUNDING).setRefundId(hcWxPayRefund.getId()));
                } else {
                    //如果不足以退款，则退钱到钱包中去
                    //计算微信需要退款的金额
                    BigDecimal wxRefundAmount = new BigDecimal(hcWxPay.getAmountTotal() - refundTotal).divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);

                    System.out.println("============= 退款到微信的金额 元：" + wxRefundAmount);

                    //计算钱包需要退款的金额
                    BigDecimal walletAmount = hcOrderMerchant.getTotalPrice().subtract(wxRefundAmount);
                    System.out.println("============= 退款到钱包的金额 元：" + walletAmount);

                    HcOrderMerchant hcOrderMerchantUpd = new HcOrderMerchant().setId(hcOrderMerchant.getId()).setState(HcOrderStateEnum.CANCELED);

                    if (walletAmount.add(wxRefundAmount).compareTo(hcOrderMerchant.getTotalPrice()) == 0 && walletAmount.compareTo(new BigDecimal(0)) > 0) {
                        if (wxRefundAmount.compareTo(new BigDecimal(0)) > 0) {
                            HcWxPayRefund payRefund = hcWxPayRefundService.refund(hcWxPay.getOutTradeNo(), hcOrder.getUserId(), hcWxPay.getAmountTotal(), wxRefundAmount);
                            hcOrderMerchantUpd.setState(HcOrderStateEnum.REFUNDING).setRefundId(payRefund.getId());
                        }

                        HcWallet wallet = new HcWallet().setUserId(hcOrder.getUserId()).setSource(HcWalletSourceEnum.REFUND).setAmount(walletAmount).setRelationId(hcOrderMerchant.getId());

                        hcWalletService.save(wallet);
                        hcOrderMerchantUpd.setRefundWalletId(wallet.getId());

                        this.updateById(hcOrderMerchantUpd);
                    } else {
                        throw new JeecgBootException("系统错误，请联系管理员");
                    }
                }
            }
        } else if (hcOrder.getPaymentMethod().equals(HcPaymentMethodEnum.ALIPAY) || hcOrder.getPaymentMethod().equals(HcPaymentMethodEnum.WALLET_ALIPAY) || hcOrder.getPaymentMethod().equals(HcPaymentMethodEnum.PC_ZFB)) {
            HcAliPay hcAliPay = hcAliPayService.getById(hcOrder.getPaymentId());

            if (hcOrder.getPaymentMethod().equals(HcPaymentMethodEnum.ALIPAY) || hcOrder.getPaymentMethod().equals(HcPaymentMethodEnum.PC_ZFB)) {
                //处理支付宝退款
                HcAliRefund refund = hcAliRefundService.refund(hcAliPay.getOutTradeNo(), hcOrder.getUserId(), hcOrderMerchant.getTotalPrice());
                this.updateById(new HcOrderMerchant().setId(hcOrderMerchant.getId()).setState(HcOrderStateEnum.REFUNDING).setRefundId(refund.getId()));
            } else if (hcOrder.getPaymentMethod().equals(HcPaymentMethodEnum.WALLET_ALIPAY)) {
                //获取当前订单下已退款的数据
                List<HcOrderMerchant> hcOrderMerchantList = this.list(new LambdaQueryWrapper<HcOrderMerchant>().eq(HcOrderMerchant::getOrderId, hcOrder.getId()).in(HcOrderMerchant::getState, HcOrderStateEnum.CANCELED, HcOrderStateEnum.REFUNDING));

                BigDecimal refund = hcOrderMerchant.getTotalPrice();
                BigDecimal refundTotal = new BigDecimal(0);
                System.out.println("============= 需要退款的金额 元：" + refund);
                if (!CollectionUtils.isEmpty(hcOrderMerchantList)) {
                    for (HcOrderMerchant orderMerchant : hcOrderMerchantList) {
                        if (StringUtils.isNotBlank(orderMerchant.getRefundId())) {
                            HcAliRefund payRefund = hcAliRefundService.getById(orderMerchant.getRefundId());
                            refund = refund.add(payRefund.getRefundAmount());
                            refundTotal = refundTotal.add(payRefund.getRefundAmount());
                        }

                        if (StringUtils.isNotBlank(orderMerchant.getRefundWalletId())) {
                            HcWallet wallet = hcWalletService.getById(orderMerchant.getRefundWalletId());
                            refund = refund.add(wallet.getAmount());
                        }
                    }
                }
                System.out.println("============= 总退款的金额 元：" + refund);
                //如果付款金额大于总退款金额 则直接调用微信退款
                if (hcAliPay.getTotalAmount().compareTo(refund) >= 0) {
                    HcAliRefund hcWxPayRefund = hcAliRefundService.refund(hcAliPay.getOutTradeNo(), hcOrder.getUserId(), hcOrderMerchant.getTotalPrice());
                    this.updateById(new HcOrderMerchant().setId(hcOrderMerchant.getId()).setState(HcOrderStateEnum.REFUNDING).setRefundId(hcWxPayRefund.getId()));
                } else {
                    //如果不足以退款，则退钱到钱包中去
                    //计算微信需要退款的金额
                    BigDecimal wxRefundAmount = hcAliPay.getTotalAmount().subtract(refundTotal);

                    System.out.println("============= 退款到微信的金额 元：" + wxRefundAmount);

                    //计算钱包需要退款的金额
                    BigDecimal walletAmount = hcOrderMerchant.getTotalPrice().subtract(wxRefundAmount);
                    System.out.println("============= 退款到钱包的金额 元：" + walletAmount);

                    HcOrderMerchant hcOrderMerchantUpd = new HcOrderMerchant().setId(hcOrderMerchant.getId()).setState(HcOrderStateEnum.CANCELED);

                    if (walletAmount.add(wxRefundAmount).compareTo(hcOrderMerchant.getTotalPrice()) == 0 && walletAmount.compareTo(new BigDecimal(0)) > 0) {
                        if (wxRefundAmount.compareTo(new BigDecimal(0)) > 0) {
                            HcAliRefund payRefund = hcAliRefundService.refund(hcAliPay.getOutTradeNo(), hcOrder.getUserId(), wxRefundAmount);
                            hcOrderMerchantUpd.setState(HcOrderStateEnum.REFUNDING).setRefundId(payRefund.getId());
                        }

                        HcWallet wallet = new HcWallet().setUserId(hcOrder.getUserId()).setSource(HcWalletSourceEnum.REFUND).setAmount(walletAmount).setRelationId(hcOrderMerchant.getId());

                        hcWalletService.save(wallet);
                        hcOrderMerchantUpd.setRefundWalletId(wallet.getId());

                        this.updateById(hcOrderMerchantUpd);
                    } else {
                        throw new JeecgBootException("系统错误，请联系管理员");
                    }
                }
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void orderJob() {
        //把所有已付款的订单改成已完成
        hcOrderService.update(new HcOrder().setState(HcOrderStateEnum.COMPLETED), new LambdaQueryWrapper<HcOrder>().eq(HcOrder::getState, HcOrderStateEnum.PAY));

        this.update(new HcOrderMerchant().setState(HcOrderStateEnum.COMPLETED), new LambdaQueryWrapper<HcOrderMerchant>().eq(HcOrderMerchant::getState, HcOrderStateEnum.PAY));

        //把所有门店的状态改成未接单和未取餐
        hcMerchantService.update(new HcMerchant().setStoreStatus(HcStoreStatusEnum.NO).setDeliveryStatus(HcDeliveryStatusEnum.NO), null);

        //分享返现
        List<HcOrder> list = hcOrderService.list(new LambdaQueryWrapper<HcOrder>().ne(HcOrder::getShareUserId, "").eq(HcOrder::getWalletId, ""));

        if (!CollectionUtils.isEmpty(list)) {
            try {
                Map<String, String> allSystemConf = hcSystemConfService.getAllSystemConf();
                BigDecimal amount_of_shared_cash_back = new BigDecimal(allSystemConf.get(HcSystemConfKeyEnum.AMOUNT_OF_SHARED_CASH_BACK.getValue()));

                for (HcOrder hcOrder : list) {
                    //获取用户下单最早的一条数据
                    HcOrder one = hcOrderService.getOne(new LambdaQueryWrapper<HcOrder>().eq(HcOrder::getUserId, hcOrder.getUserId()).orderByAsc(HcOrder::getCreateTime).last(" limit 1 "));

                    //判断分享的订单数据和最早下单的数据id是否一致
                    if (hcOrder.getId().equals(one.getId()) && !hcOrder.getShareUserId().equals(hcOrder.getUserId())) {
                        //钱包内增加余额
                        HcWallet hcWallet = new HcWallet().setUserId(hcOrder.getShareUserId()).setAmount(amount_of_shared_cash_back).setSource(HcWalletSourceEnum.SHARE).setCreateBy("admin").setCreateTime(new Date()).setRelationId(hcOrder.getId());

                        hcWalletService.save(hcWallet);

                        hcOrderService.updateById(new HcOrder().setId(hcOrder.getId()).setWalletId(hcWallet.getId()));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public Map getOrderStatisticsOfGlobalPage(String beginTime, String endTime) {
        return hcOrderMerchantMapper.getOrderStatisticsOfGlobalPage(beginTime, endTime);
    }

    @Override
    public IPage<HcOrderMerchant> getOrderListOfGlobalPage(Page<HcOrderMerchant> page, HcOrderMerchant param) {
        IPage<HcOrderMerchant> orderListOfGlobalPage = hcOrderMerchantMapper.getOrderListOfGlobalPage(page, param);

        for (HcOrderMerchant record : orderListOfGlobalPage.getRecords()) {
            this.setInformation(record);
        }

        return orderListOfGlobalPage;
    }

    @Override
    public List<HcMerchantData> getMerchantDataList(String merchantId) throws ParseException {
        List<HcMerchantData> result = new ArrayList<>();
        HcMerchantData hcMerchantData1 = hcOrderMerchantMapper.getHcMerchantData(merchantId);
//        HcMerchantData hcMerchantData1 = hcOrderMerchantMapper.getHcMerchantDataNew(merchantId);
        if (null != hcMerchantData1){
            Calendar maxCalendar = Calendar.getInstance();
//        maxCalendar.setTime(hcMerchantData1.getMaxDate());

            Calendar minCalendar = Calendar.getInstance();
            minCalendar.setTime(hcMerchantData1.getMinDate());

            //计算日期差
            int d = DateUtils.dateDiff('d', DateUtils.parseCalendar(DateUtils.formatDate(maxCalendar, "yyyy-MM-dd"), "yyyy-MM-dd"), DateUtils.parseCalendar(DateUtils.formatDate(minCalendar, "yyyy-MM-dd"), "yyyy-MM-dd"));

            if (maxCalendar.getTime().after(DateUtils.parseDate(DateUtils.formatDate(maxCalendar, "yyyy-MM-dd") + " 18:00:00", "yyyy-MM-dd HH:mm:ss"))) {
                d++;
                maxCalendar.add(Calendar.DAY_OF_MONTH, 1);
            }

            if (minCalendar.getTime().before(DateUtils.parseDate(DateUtils.formatDate(minCalendar, "yyyy-MM-dd") + " 18:00:00", "yyyy-MM-dd HH:mm:ss"))) {
                d++;
            }

            for (int i = 0; i < d; i++) {
                String beginTime = "";
                String endTime = DateUtils.formatDate(maxCalendar, "yyyy-MM-dd") + " 18:00:00";

                Calendar instance = Calendar.getInstance();
                instance.setTime(maxCalendar.getTime());
                instance.add(Calendar.DAY_OF_MONTH, -1);
                beginTime = DateUtils.formatDate(instance, "yyyy-MM-dd") + " 18:00:01";

                HcMerchantData merchantDataRecord = hcOrderMerchantMapper.getMerchantDataRecord(merchantId, beginTime, endTime);

                if (merchantDataRecord == null) {
                    merchantDataRecord = new HcMerchantData().setTodayIncome(new BigDecimal(0)).setEffectiveQuantity(0L).setAfterSalesRecords(0L);
                }

                merchantDataRecord.setDateStr(DateUtils.formatDate(maxCalendar, "yyyy年MM月dd日"));

                List<HcMerchantSettlement> hcMerchantSettlementList = hcMerchantSettlementService.list(new LambdaQueryWrapper<HcMerchantSettlement>()
                        .eq(HcMerchantSettlement::getMerchantId, merchantId)
                        .eq(HcMerchantSettlement::getType, HcMerchantSettlementTypeEnum.CHANGE)
                        .between(HcMerchantSettlement::getCreateTime, beginTime, endTime)
                );

                HcMerchantSettlement one = hcMerchantSettlementService.getOne(new LambdaQueryWrapper<HcMerchantSettlement>()
                        .eq(HcMerchantSettlement::getMerchantId, merchantId)
                        .eq(HcMerchantSettlement::getType, HcMerchantSettlementTypeEnum.SETTLED)
                        .eq(HcMerchantSettlement::getSettlementDate, DateUtils.formatDate(maxCalendar, "yyyy-MM-dd"))
                );

                if (one != null) {
                    merchantDataRecord.setSettlementType(one.getType());
                }

                if (!CollectionUtils.isEmpty(hcMerchantSettlementList)) {
                    BigDecimal reduce = hcMerchantSettlementList.stream().map(HcMerchantSettlement::getSettlementAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                    merchantDataRecord.setTodayIncome(merchantDataRecord.getTodayIncome().add(reduce));
                }

                merchantDataRecord.setHcMerchantSettlementList(hcMerchantSettlementList);
                result.add(merchantDataRecord);
                maxCalendar.add(Calendar.DAY_OF_MONTH, -1);
            }
        }
        return result;
    }

    public ModelAndView platformExportXls(HcOrderMerchant param) {
        Page<HcOrderMerchant> page = new Page<>(1, -1);

        if (StringUtils.isNotBlank(param.getSelections())) {
            param.setIds(Arrays.asList(param.getSelections().split(",")));
        }

        if (StringUtils.isNotBlank(param.getTimeBegin()) && param.getTimeBegin().length() == 16) {
            param.setTimeBegin(param.getTimeBegin() + ":00");
        }
        if (StringUtils.isNotBlank(param.getTimeEnd()) && param.getTimeEnd().length() == 16) {
            param.setTimeEnd(param.getTimeEnd() + ":00");
        }

        IPage<HcOrderMerchant> pageList = hcOrderMerchantMapper.pageList(page, param);
        List<HcOrderMerchant> list = pageList.getRecords();

        for (HcOrderMerchant hcOrderMerchant : list) {
            this.setInformation(hcOrderMerchant);
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.CLASS, HcOrderMerchant.class);
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams();
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
//        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
//        mv.addObject(NormalExcelConstants.DATA_LIST, list);

        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, HcOrderMerchantExport.class, list);
        MultipartFile multipartFile = HcUtils.workbookToCommonsMultipartFile(sheets, param.getStoreName() + DateUtils.formatDate(new Date(), "yyyy-MM-dd-HH-mm") + ".xls");
        CommonUtils.upload(multipartFile, "exportExcel", "alioss");

        return mv;
    }

    public String platformExportXls2(HcOrderMerchant param) {
        Page<HcOrderMerchant> page = new Page<>(1, -1);

        if (StringUtils.isNotBlank(param.getSelections())) {
            param.setIds(Arrays.asList(param.getSelections().split(",")));
        }

        if (StringUtils.isNotBlank(param.getTimeBegin()) && param.getTimeBegin().length() == 16) {
            param.setTimeBegin(param.getTimeBegin() + ":00");
        }
        if (StringUtils.isNotBlank(param.getTimeEnd()) && param.getTimeEnd().length() == 16) {
            param.setTimeEnd(param.getTimeEnd() + ":00");
        }

        IPage<HcOrderMerchant> pageList = hcOrderMerchantMapper.pageList(page, param);
        List<HcOrderMerchant> list = pageList.getRecords();

        for (HcOrderMerchant hcOrderMerchant : list) {
            this.setInformation(hcOrderMerchant);
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.CLASS, HcOrderMerchant.class);
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams();
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
//        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
//        mv.addObject(NormalExcelConstants.DATA_LIST, list);

        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, HcOrderMerchant.class, list);
        MultipartFile multipartFile = HcUtils.workbookToCommonsMultipartFile(sheets, param.getStoreName() + DateUtils.formatDate(new Date(), "yyyy-MM-dd-HH-mm") + ".xls");
        String excelFileUrl = CommonUtils.upload(multipartFile, "exportExcel", "alioss");

        JSONObject resultData = new JSONObject();
        resultData.put("fileUrl", excelFileUrl);

        return resultData.toJSONString();
    }

    @Transactional(rollbackFor = Exception.class)
    public String exportXls(String merchantId, List<String> ids, String type) {
        HcMerchant hcMerchant = hcMerchantService.getById(merchantId);
        List<HcOrderMerchantExport> exportList = hcOrderMerchantMapper.getExportList(merchantId, ids, type);

        for (HcOrderMerchantExport record : exportList) {
            //获取下单的菜品
            List<HcOrderDetailed> hcOrderDetailedList = hcOrderDetailedService.list(new LambdaQueryWrapper<HcOrderDetailed>()
                    .select(HcOrderDetailed::getTradeName, HcOrderDetailed::getCommodityQuantity, HcOrderDetailed::getSpecifications)
                    .eq(HcOrderDetailed::getOrderMerchantId, record.getId())
            );

            try {
                //按照菜品名称排序
                List<HcOrderDetailed> collect = hcOrderDetailedList.stream().sorted(Comparator.comparing(HcOrderDetailed::getTradeName, (x, y) -> {
                    Collator clt = Collator.getInstance(java.util.Locale.CHINA);
                    return clt.compare(x, y);
                })).collect(Collectors.toList());

                record.setNameDishes(collect.stream().map(r -> {
                    String result = r.getTradeName();

                    if (StringUtils.isNotBlank(r.getSpecifications())) {
                        result += "(" + r.getSpecifications() + ")";
                    }

                    return result + "x" + r.getCommodityQuantity();
                }).collect(Collectors.joining("+")));
            } catch (Exception e) {
                log.error("菜品排序报错，菜品集合：{}", JSON.toJSONString(hcOrderDetailedList));
            }
        }

        List<HcOrderMerchantExport> sortList = exportList.stream().sorted(Comparator.comparing(HcOrderMerchantExport::getNameDishes, (x, y) -> {
            Collator clt = Collator.getInstance(Locale.CHINA);
            return clt.compare(x, y);
        })).collect(Collectors.toList());

        // Step.3 AutoPoi 导出Excel
//        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
//        mv.addObject(NormalExcelConstants.CLASS, HcOrderMerchantExport.class);
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams();
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
//        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
//        mv.addObject(NormalExcelConstants.DATA_LIST, sortList);

        if ("merchant".equals(type)) {
            for (HcOrderMerchantExport hcOrderMerchantExport : sortList) {
                this.updateById(new HcOrderMerchant().setId(hcOrderMerchantExport.getId()).setExportFlag(1));
            }
        }

        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, HcOrderMerchantExport.class, sortList);
        MultipartFile multipartFile = HcUtils.workbookToCommonsMultipartFile(sheets, hcMerchant.getStoreName() + DateUtils.formatDate(new Date(), "yyyy-MM-dd-HH-mm") + ".xls");
        return CommonUtils.upload(multipartFile, "exportExcel", "alioss");
    }

    @Transactional(rollbackFor = Exception.class)
    public String exportXlsNew(String merchantId, List<String> ids, String type) {
        HcMerchant hcMerchant = hcMerchantService.getById(merchantId);
        List<HcOrderMerchantExport> exportList = hcOrderMerchantMapper.getExportList(merchantId, ids, type);

        for (HcOrderMerchantExport record : exportList) {
            //获取下单的菜品
            List<HcOrderDetailed> hcOrderDetailedList = hcOrderDetailedService.list(new LambdaQueryWrapper<HcOrderDetailed>()
                    .select(HcOrderDetailed::getTradeName, HcOrderDetailed::getCommodityQuantity, HcOrderDetailed::getSpecifications)
                    .eq(HcOrderDetailed::getOrderMerchantId, record.getId())
            );

            try {
                //按照菜品名称排序
                List<HcOrderDetailed> collect = hcOrderDetailedList.stream().sorted(Comparator.comparing(HcOrderDetailed::getTradeName, (x, y) -> {
                    Collator clt = Collator.getInstance(java.util.Locale.CHINA);
                    return clt.compare(x, y);
                })).collect(Collectors.toList());

                record.setNameDishes(collect.stream().map(r -> {
                    String result = r.getTradeName();

                    if (StringUtils.isNotBlank(r.getSpecifications())) {
                        result += "(" + r.getSpecifications() + ")";
                    }

                    return result + "x" + r.getCommodityQuantity();
                }).collect(Collectors.joining("+")));
            } catch (Exception e) {
                log.error("菜品排序报错，菜品集合：{}", JSON.toJSONString(hcOrderDetailedList));
            }
        }

        //获取相关联的企业
        List<String> hcCompanyIds = hcCompanyMerchantInfoMapper.selectList(new LambdaQueryWrapper<HcCompanyMerchantInfo>()
                .eq(HcCompanyMerchantInfo::getMerchantId, merchantId)).stream().map(HcCompanyMerchantInfo::getCompanyId).collect(Collectors.toList());

        List<HcOrderMerchantExport> hcOrderDetailedList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(hcCompanyIds)){
            List<HcCompanyFoodOrder> companyFoodOrders = hcCompanyFoodOrderMapper
                    .selectList(new LambdaQueryWrapper<HcCompanyFoodOrder>()
                            .eq(HcCompanyFoodOrder::getState, HcOrderStateEnum.UNCOMPLETED)
                            .eq(HcCompanyFoodOrder::getMerchantId,merchantId)
                            .in(HcCompanyFoodOrder::getCompanyId,hcCompanyIds)
                            .orderByDesc(HcCompanyFoodOrder::getCreateTime));

            List<String> allFoodName = new ArrayList<>();
            List<HcOrderDetailed> hcOrderDetailedLists = new ArrayList<>();
            for (HcCompanyFoodOrder hcfo : companyFoodOrders) {
                List<String> foodName = new ArrayList<>();
                HcOrderMerchantExport h = new HcOrderMerchantExport();
                h.setId(hcfo.getId());
                HcOrderDetailed hcOrderDetailed = new HcOrderDetailed();
                //地址
                String pickupAddressId = hcfo.getPickupAddressId();
                HcCompanyPickupAddress pickupAddress = hcCompanyPickupAddressService.getOne(new LambdaQueryWrapper<HcCompanyPickupAddress>().eq(HcCompanyPickupAddress::getId, pickupAddressId));
                if (null != pickupAddress){
                    h.setSupplyAddress(pickupAddress.getAddressCode());
                }
                //取餐号
                h.setPickingSerialNo(hcfo.getPickingSerialNo());
                h.setNameTakingMeal(hcfo.getUsername());
                JSONObject foodInfo = JSONObject.parseObject(hcfo.getFoodInfo());
                JSONObject foodObject = foodInfo.getJSONObject("food");
                HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);
                //商品数量
                int foodNum = (int) foodInfo.get("foodNum");
                // 获取 foodsSpecification 列表
                JSONArray foodsSpecificationArray = foodInfo.getJSONArray("foodsSpecification");
                // 将 JSONArray 转换为 List<String>
                List<HcCompanyFoodSpecifications> foodsSpecificationList = new ArrayList<>();
                if (foodsSpecificationArray!=null){
                    foodsSpecificationList = foodsSpecificationArray.toJavaList(HcCompanyFoodSpecifications.class);
                    List<String> collect = foodsSpecificationList.stream().map(f -> f.getSpecificationName()).collect(Collectors.toList());
                    foodName.add(hcCompanyFoodList.getFoodName()+"("+Joiner.on(",").join(collect) +") x"+ foodNum);
                }else {
                    foodName.add(hcCompanyFoodList.getFoodName()+"x"+ foodNum);
                }
                hcOrderDetailed.setTradeName(Joiner.on("+").join(foodName));
                h.setNameDishes(Joiner.on("+").join(foodName));
                hcOrderDetailedLists.add(hcOrderDetailed);
                h.setRemarks(hcfo.getRemark());
                allFoodName.addAll(foodName);
                hcOrderDetailedList.add(h);

                if ("merchant".equals(type)|| com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(ids)) {
                    hcCompanyFoodOrderMapper.updateByOrderNum(hcfo.getOrderNum(),merchantId);
                }
            }
        }
        exportList.addAll(hcOrderDetailedList);

        List<HcOrderMerchantExport> sortList = exportList.stream().sorted(Comparator.comparing(HcOrderMerchantExport::getNameDishes, (x, y) -> {
            Collator clt = Collator.getInstance(Locale.CHINA);
            return clt.compare(x, y);
        })).collect(Collectors.toList());

        ExportParams exportParams = new ExportParams();
        exportParams.setImageBasePath(upLoadPath);

        if ("merchant".equals(type)) {
            for (HcOrderMerchantExport hcOrderMerchantExport : sortList) {
                this.updateById(new HcOrderMerchant().setId(hcOrderMerchantExport.getId()).setExportFlag(1));
            }
        }

        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, HcOrderMerchantExport.class, sortList);
        MultipartFile multipartFile = HcUtils.workbookToCommonsMultipartFile(sheets, hcMerchant.getStoreName() + DateUtils.formatDate(new Date(), "yyyy-MM-dd-HH-mm") + ".xls");
        return CommonUtils.upload(multipartFile, "exportExcel", "alioss");
    }

    public HcMerchant getOrderStatistics(String merchantId) {
        HcMerchant result = hcMerchantService.getById(merchantId);

        //获取统计订单时间和公告
        Map<String, String> allSystemConf = hcSystemConfService.getAllSystemConf();
        result.setOrderStatisticsTimeBegin(allSystemConf.get(HcSystemConfKeyEnum.ORDER_STATISTICS_TIME_BEGIN.getValue()));
        result.setOrderStatisticsTimeEnd(allSystemConf.get(HcSystemConfKeyEnum.ORDER_STATISTICS_TIME_END.getValue()));
        result.setMerchantAnnouncement(allSystemConf.get(HcSystemConfKeyEnum.MERCHANT_ANNOUNCEMENT.getValue()));

//        //获取统计单量列表
        List<HcOrderDetailed> hcOrderDetailedList = hcOrderMerchantMapper.getOrderStatistics(merchantId);
        //获取企业订单
        //只有启用个人点餐菜品的才展示在这里
        LambdaQueryWrapper<HcCompanyMerchantInfo> companyMerchantInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        companyMerchantInfoLambdaQueryWrapper.eq(HcCompanyMerchantInfo::getMerchantId,merchantId);
        List<HcCompanyMerchantInfo> hcCompanyMerchantInfos = hcCompanyMerchantInfoMapper.selectList(companyMerchantInfoLambdaQueryWrapper);
        List<String> companyIds = hcCompanyMerchantInfos.stream().map(HcCompanyMerchantInfo::getCompanyId).collect(Collectors.toList());
        LambdaQueryWrapper<HcCompanyInfo> companyInfoLambdaQueryWrapper = new LambdaQueryWrapper<HcCompanyInfo>();
        if (!CollectionUtils.isEmpty(companyIds)){
            companyInfoLambdaQueryWrapper.in(HcCompanyInfo::getId, companyIds);
        }
        List<HcCompanyInfo> companyInfos = hcCompanyInfoMapper.selectList(companyInfoLambdaQueryWrapper).stream().filter(h -> h.getIsOpenPrivateOrder().equalsIgnoreCase("yes") && h.getState().equals("yes")).collect(Collectors.toList());
        List<HcOrderDetailed> orderDetailedList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(companyInfos)) {
            List<String> companyIdList = companyInfos.stream().map(HcCompanyInfo::getId).collect(Collectors.toList());
            LambdaQueryWrapper<HcCompanyFoodOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getMerchantId, merchantId)
                    .eq(HcCompanyFoodOrder::getState, HcOrderStateEnum.UNCOMPLETED);
            if (!CollectionUtils.isEmpty(companyIdList)) {
                orderLambdaQueryWrapper.in(HcCompanyFoodOrder::getCompanyId, companyIdList);
            }
            List<HcCompanyFoodOrder> hcCompanyFoodOrders = hcCompanyFoodOrderMapper.selectList(orderLambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(hcCompanyFoodOrders)){
                for (HcCompanyFoodOrder order : hcCompanyFoodOrders) {
                    JSONObject foodInfo = JSONObject.parseObject(order.getFoodInfo());
                    //商品数量
                    Integer foodNum = (Integer) foodInfo.get("foodNum");
                    JSONObject foodObject = foodInfo.getJSONObject("food");
                    HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);

                    HcOrderDetailed h = new HcOrderDetailed();
                    List<String> foodName = new ArrayList<>();
                    // 获取 foodsSpecification 列表
                    JSONArray foodsSpecificationArray = foodInfo.getJSONArray("foodsSpecification");
                    // 将 JSONArray 转换为 List<String>
                    List<HcCompanyFoodSpecifications> foodsSpecificationList = new ArrayList<>();
                    if (foodsSpecificationArray!=null){
                        foodsSpecificationList = foodsSpecificationArray.toJavaList(HcCompanyFoodSpecifications.class);
                        List<String> collect = foodsSpecificationList.stream().map(f -> f.getSpecificationName()).collect(Collectors.toList());
                        foodName.add(hcCompanyFoodList.getFoodName()+"("+Joiner.on(",").join(collect) +")");
                    }else {
                        foodName.add(hcCompanyFoodList.getFoodName());
                    }
//                    h.setTradeName(hcCompanyFoodList.getFoodName());
                    h.setTradeName(Joiner.on("+").join(foodName));
                    h.setCommodityQuantity(foodNum);

                    if (orderDetailedList.size() > 0) {
                        boolean found = false;
                        for (HcOrderDetailed hcOrderDetailed : orderDetailedList) {
                            if (hcOrderDetailed.getTradeName().equals(h.getTradeName())) {
                                hcOrderDetailed.setCommodityQuantity(hcOrderDetailed.getCommodityQuantity() + foodNum);
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            orderDetailedList.add(h);
                        }
                    } else {
                        orderDetailedList.add(h);
                    }
                }
            }
        }
        hcOrderDetailedList.addAll(orderDetailedList);
        result.setHcOrderDetailedList(hcOrderDetailedList);

        //获取未导出的数量
        long count = this.count(new LambdaQueryWrapper<HcOrderMerchant>().eq(HcOrderMerchant::getMerchantId, merchantId).eq(HcOrderMerchant::getState, HcOrderStateEnum.PAY).eq(HcOrderMerchant::getExportFlag, 0));

        result.setNotExportedCount(count);

        return result;
    }

    public IPage<HcOrderMerchant> getOrderListByMerchantId(Page<HcOrderMerchant> page, String merchantId) {
        IPage<HcOrderMerchant> hcOrderMerchantPage = hcOrderMerchantMapper.getPayOrderListByMerchantId(page, merchantId);
        List<HcOrderMerchant> records = hcOrderMerchantPage.getRecords();
        for (HcOrderMerchant record : records ) {
            //获取下单的菜品
            List<HcOrderDetailed> hcOrderDetailedList = hcOrderDetailedService.list(new LambdaQueryWrapper<HcOrderDetailed>()
                    .eq(HcOrderDetailed::getOrderMerchantId, record.getId()));

            try {
                //按照菜品名称排序
                List<HcOrderDetailed> collect = hcOrderDetailedList.stream().sorted(Comparator.comparing(HcOrderDetailed::getTradeName, (x, y) -> {
                    Collator clt = Collator.getInstance(java.util.Locale.CHINA);
                    return clt.compare(x, y);
                })).collect(Collectors.toList());
                //暂存下单第一个菜品的名称，用来排序
                record.setNameDishes(collect.get(0).getTradeName());
                record.setHcOrderDetailedList(collect);
            } catch (Exception e) {
                log.error("菜品排序报错，菜品集合：{}", JSON.toJSONString(hcOrderDetailedList));
            }
        }

        //添加企业订单
        //只有启用个人点餐菜品的才展示在这里
        LambdaQueryWrapper<HcCompanyMerchantInfo> companyMerchantInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        companyMerchantInfoLambdaQueryWrapper.eq(HcCompanyMerchantInfo::getMerchantId,merchantId);
        List<HcCompanyMerchantInfo> hcCompanyMerchantInfos = hcCompanyMerchantInfoMapper.selectList(companyMerchantInfoLambdaQueryWrapper);
        List<String> companyIds = hcCompanyMerchantInfos.stream().map(HcCompanyMerchantInfo::getCompanyId).collect(Collectors.toList());
        LambdaQueryWrapper<HcCompanyInfo> companyInfoLambdaQueryWrapper = new LambdaQueryWrapper<HcCompanyInfo>();

        if (!CollectionUtils.isEmpty(companyIds)){
//            List<String> companyIdsList = new ArrayList<>();
//            //获取开启了个人订单的企业
//            companyIds.forEach(c -> {
//                HcCompanyInfo hcCompanyInfo = hcCompanyInfoMapper.selectOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, c));
//                if (null != hcCompanyInfo){
//                    if (hcCompanyInfo.getIsOpenPrivateOrder().equals("yes")){
//                        companyIdsList.add(c);
//                    }
//                }
//            });
            companyInfoLambdaQueryWrapper.in(HcCompanyInfo::getId, companyIds);
        }
//        List<HcCompanyInfo> companyInfos = hcCompanyInfoMapper.selectList(companyInfoLambdaQueryWrapper)
//                .stream().filter(h -> h.getIsOpenPrivateOrder().equalsIgnoreCase("yes") && h.getState().equals("yes")).collect(Collectors.toList());
        List<HcCompanyInfo> companyInfos = hcCompanyInfoMapper.selectList(companyInfoLambdaQueryWrapper)
                .stream().filter(h -> h.getIsOpenPrivateOrder().equalsIgnoreCase("yes")).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(companyInfos)){
            List<String> companyIdList = companyInfos.stream().map(HcCompanyInfo::getId).collect(Collectors.toList());
            LambdaQueryWrapper<HcCompanyFoodOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getMerchantId,merchantId)
                    .eq(HcCompanyFoodOrder::getState,HcOrderStateEnum.UNCOMPLETED);
        if (!CollectionUtils.isEmpty(companyIdList)){
            orderLambdaQueryWrapper.in(HcCompanyFoodOrder::getCompanyId,companyIdList);
        }
            List<HcCompanyFoodOrder> hcCompanyFoodOrders = hcCompanyFoodOrderMapper.selectList(orderLambdaQueryWrapper);
            List<String> orderNums = hcCompanyFoodOrders.stream().map(HcCompanyFoodOrder::getOrderNum).distinct().collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(orderNums)){
                for (String orderNum : orderNums) {
                    HcOrderMerchant h = new HcOrderMerchant();
                    List<HcOrderDetailed> hcOrderDetailedLists = new ArrayList<>();
                    List<HcCompanyFoodOrder> companyFoodOrders = hcCompanyFoodOrderMapper.selectList(new LambdaQueryWrapper<HcCompanyFoodOrder>().eq(HcCompanyFoodOrder::getOrderNum, orderNum).eq(HcCompanyFoodOrder::getMerchantId,merchantId));
                    HcCompanyInfo hcCompanyInfo = hcCompanyInfoMapper.selectOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, companyFoodOrders.get(0).getCompanyId()));
                    h.setCompanyName(hcCompanyInfo.getCompanyName());
                    h.setRemarks(companyFoodOrders.get(0).getRemark());
                    HcOrderDetailed hcOrderDetailed = new HcOrderDetailed();
                    List<String> foodName = new ArrayList<>();
                    //价格
                    BigDecimal foodPrice = new BigDecimal(0);
                    //合作价格
                    BigDecimal coopPrice = new BigDecimal(0);
                    for (HcCompanyFoodOrder hcCompanyFoodOrder : companyFoodOrders) {

                        h.setState(hcCompanyFoodOrder.getState());
                        HcMerchant hcMerchant = hcMerchantService.getOne(new LambdaQueryWrapper<HcMerchant>().eq(HcMerchant::getId,hcCompanyFoodOrder.getMerchantId()));
                        h.setStoreName(hcMerchant.getStoreName());
                        h.setCreateTime(hcCompanyFoodOrder.getCreateTime());
                        //地址
                        String pickupAddressId = hcCompanyFoodOrder.getPickupAddressId();
                        HcCompanyPickupAddress pickupAddress = hcCompanyPickupAddressMapper.selectOne(new LambdaQueryWrapper<HcCompanyPickupAddress>().eq(HcCompanyPickupAddress::getId, pickupAddressId));
                        h.setSupplyAddress(pickupAddress.getAddressCode());
                        //取餐号
                        h.setPickingSerialNo(hcCompanyFoodOrder.getPickingSerialNo());
                        h.setNameTakingMeal(hcCompanyFoodOrder.getUsername());
                        h.setSupplyAddress(pickupAddress.getAddressCode());
                        JSONObject foodInfo = JSONObject.parseObject(hcCompanyFoodOrder.getFoodInfo());
                        JSONObject foodObject = foodInfo.getJSONObject("food");
                        HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);
                        //商品数量
                        int foodNum = (int) foodInfo.get("foodNum");
                        // 获取 foodsSpecification 列表
                        JSONArray foodsSpecificationArray = foodInfo.getJSONArray("foodsSpecification");
                        // 将 JSONArray 转换为 List<String>
                        List<HcCompanyFoodSpecifications> foodsSpecificationList = new ArrayList<>();
                        if (foodsSpecificationArray!=null){
                            foodsSpecificationList = foodsSpecificationArray.toJavaList(HcCompanyFoodSpecifications.class);
                            List<String> collect = foodsSpecificationList.stream().map(f -> f.getSpecificationName()).collect(Collectors.toList());
                            foodName.add(hcCompanyFoodList.getFoodName()+"("+Joiner.on(",").join(collect) +")");
                        }else {
                            foodName.add(hcCompanyFoodList.getFoodName());
                        }
//                        foodName.add(hcCompanyFoodList.getFoodName());
                        if (hcCompanyFoodList.getCooperatePrice()==null||hcCompanyFoodList.getCooperatePrice().compareTo(new BigDecimal(0)) == 0){
                            //获取门店价格
                            HcCompanyMerchantSetting companyMerchantSetting = hcCompanyMerchantSettingMapper.selectOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
                                    .eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
                                    .eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
                            if (null == companyMerchantSetting){
                                companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0)).setSalePrice(new BigDecimal(0));
                            }
                            if (companyMerchantSetting.getMerchantCooperatePrice()==null||companyMerchantSetting.getMerchantCooperatePrice().compareTo(new BigDecimal(0))==0){
                                //获取企业合作价格
                                foodPrice = foodPrice.add(hcCompanyInfo.getMerchantPrice());
                            }else {
                                foodPrice = foodPrice.add(companyMerchantSetting.getMerchantCooperatePrice());
                            }
                        }else {
                            foodPrice = foodPrice.add(hcCompanyFoodList.getCooperatePrice());
                        }

                        if (hcCompanyFoodList.getSalePrice()==null||hcCompanyFoodList.getSalePrice().compareTo(new BigDecimal(0)) == 0){
                            //获取门店价格
                            HcCompanyMerchantSetting companyMerchantSetting = hcCompanyMerchantSettingMapper.selectOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
                                    .eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
                                    .eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
                            if (null == companyMerchantSetting){
                                companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0)).setSalePrice(new BigDecimal(0));
                            }
                            if (companyMerchantSetting.getSalePrice()==null||companyMerchantSetting.getSalePrice().compareTo(new BigDecimal(0))==0){
                                //获取企业合作价格
                                coopPrice = coopPrice.add(hcCompanyInfo.getCompanyPrice().multiply(new BigDecimal(foodNum)));
                            }else {
                                coopPrice = coopPrice.add(companyMerchantSetting.getSalePrice().multiply(new BigDecimal(foodNum)));
                            }
                        }else {
                            coopPrice = coopPrice.add(hcCompanyFoodList.getSalePrice().multiply(new BigDecimal(foodNum)));
                        }
                        hcOrderDetailed.setCommodityQuantity(foodNum);
                    }
                    hcOrderDetailed.setTradeName(Joiner.on("+").join(foodName));
                    h.setNameDishes(Joiner.on("+").join(foodName));
                    hcOrderDetailedLists.add(hcOrderDetailed);
                    h.setCommodityPrice(foodPrice);
                    h.setTotalPrice(coopPrice);
                    h.setHcOrderDetailedList(hcOrderDetailedLists);
                    records.add(h);
                }
            }
        }
        List<HcOrderMerchant> hcOrderMerchants = records.stream().sorted(Comparator.comparing(HcOrderMerchant::getNameDishes, (x, y) -> {
            Collator clt = Collator.getInstance(Locale.CHINA);
            return clt.compare(x, y);
        })).collect(Collectors.toList());

        hcOrderMerchantPage.setRecords(hcOrderMerchants);
        return hcOrderMerchantPage;
    }

    @Override
    public IPage<HcOrderMerchant> getList(Page<HcOrderMerchant> page, HcOrderMerchant param) {
        hcOrderService.checkNoPayOrder(param.getUserId());

        IPage<HcOrderMerchant> hcOrderIPage = hcOrderMerchantMapper.getList(page, param);

        for (HcOrderMerchant record : hcOrderIPage.getRecords()) {
            this.setInformation(record);

            //获取取餐点图片
            HcSiteAddressDetails hcSiteAddressDetails = hcSiteAddressDetailsService.getById(record.getAddressId());

            if (hcSiteAddressDetails != null) {
                JSONArray jsonArray = JSON.parseArray(hcSiteAddressDetails.getSupplyAddress());

                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String code = jsonObject.getString("code");

                    if (code.equals(record.getSupplyAddress())) {
                        String img = jsonObject.getString("img");
                        record.setSupplyAddressImg(img);
                        break;
                    }
                }
            }
        }

        return hcOrderIPage;
    }

    @Override
    public IPage<HcOrderMerchant> pageList(Page<HcOrderMerchant> page, HcOrderMerchant param) {
        IPage<HcOrderMerchant> pageList = hcOrderMerchantMapper.pageList(page, param);
        for (HcOrderMerchant record : pageList.getRecords()) {
            this.setInformation(record);

            if (record.getState().equals(HcOrderStateEnum.REFUNDING)) {
                HcOrder hcOrder = hcOrderService.getById(record.getOrderId());

                if (hcOrder.getPaymentMethod().equals(HcPaymentMethodEnum.WXPAY) || hcOrder.getPaymentMethod().equals(HcPaymentMethodEnum.WALLET_WXPAY) || hcOrder.getPaymentMethod().equals(HcPaymentMethodEnum.PC_WX)) {
                    HcWxPayRefund wxPayRefund = hcWxPayRefundService.queryRefund(record.getRefundId());

                    if ("SUCCESS".equals(wxPayRefund.getStatus())) {
                        this.updateById(new HcOrderMerchant().setId(record.getId()).setState(HcOrderStateEnum.CANCELED));
                        record.setState(HcOrderStateEnum.CANCELED);
                    }
                } else if (hcOrder.getPaymentMethod().equals(HcPaymentMethodEnum.ALIPAY) || hcOrder.getPaymentMethod().equals(HcPaymentMethodEnum.WALLET_ALIPAY)) {
                    try {
                        HcAliRefund aliRefund = hcAliRefundService.queryRefund(record.getRefundId());

                        if ("REFUND_SUCCESS".equals(aliRefund.getRefundStatus())) {
                            this.updateById(new HcOrderMerchant().setId(record.getId()).setState(HcOrderStateEnum.CANCELED));
                            record.setState(HcOrderStateEnum.CANCELED);
                        }
                    } catch (AlipayApiException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }

        return pageList;
    }

    @Override
    public void setInformation(HcOrderMerchant record) {
        List<HcOrderDetailed> hcOrderDetailedList = hcOrderDetailedService.list(new LambdaQueryWrapper<HcOrderDetailed>().eq(HcOrderDetailed::getOrderMerchantId, record.getId()));

        record.setHcOrderDetailedList(hcOrderDetailedList);

        HcAfterSales hcAfterSales = hcAfterSalesService.getById(record.getAfterSalesId());

        if (hcAfterSales != null) {
            record.setAfterSalesState(hcAfterSales.getState());
        }

        //获取订单的菜品名称
        HcOrderDetailed hcOrderDetailed = hcOrderDetailedService.getOne(new QueryWrapper<HcOrderDetailed>().select("GROUP_CONCAT(CONCAT(TRADE_NAME, if(SPECIFICATIONS is null, '', '('), if(SPECIFICATIONS is null, '', SPECIFICATIONS), if(SPECIFICATIONS is null, '', ')'), 'x', COMMODITY_QUANTITY) order by TRADE_NAME Separator '+') as tradeName").eq("ORDER_MERCHANT_ID", record.getId()).orderByAsc("TRADE_NAME"));

        if (hcOrderDetailed != null) {
            record.setNameDishes(hcOrderDetailed.getTradeName());
        }

        record.setOrderCount(hcOrderService.count(new LambdaQueryWrapper<HcOrder>().eq(HcOrder::getUserId, record.getUserId())));
    }

    @Override
    public IPage<HcOrderMerchant> getListByAddress(Page<HcOrderMerchant> page, HcOrderMerchant param) {
        // param.getAddressId() 为用户所属大厦id
        // select * from hc_site_address_details where id = <用户所属大厦id>
        HcSiteAddressDetails hcSiteAddressDetails = hcSiteAddressDetailsService.getById(param.getAddressId());
        // 大厦所属 站点id，比如南山，坂田，福田站点的id
        param.setSiteId(hcSiteAddressDetails.getSiteId());

        JSONObject yongShanTuanTime = HcUtils.getYongShanTuanTime();
        param.setTimeBegin(yongShanTuanTime.getString("beginTime"));
        param.setTimeEnd(yongShanTuanTime.getString("endTime"));
        // mapper.xml中的sql，以 站点id为查询条件，获取某个站点的所有订单，注意不是站点中的某个大厦的所有订单，而是整个站点所有大厦的订单
        return hcOrderMerchantMapper.getListByAddress(page, param);
    }

    private Map getAddressIdByCode(String code){
        Map<String,Object> map = new HashMap<>(2);
        AtomicReference<String> siteId = new AtomicReference<>("");
        //获取所有大厦
        List<HcSiteAddressDetails> allAddress = hcSiteAddressDetailsService.getAllAddress();
        allAddress.forEach(a->{
            String supplyAddress = a.getSupplyAddress();
            JSONArray parseArray = JSON.parseArray(supplyAddress);
            parseArray.forEach( s ->{
                AddressPojo adress = JSON.parseObject(s.toString(), new TypeReference<AddressPojo>() {
                });
                if (code.equals(adress.getCode())){
                    String pickAddress = a.getAddressName()+ adress.getName();
                    siteId.set(a.getId());
                    map.put("pickAddress",pickAddress);
                    map.put("siteId",siteId);
                }
            });
        });
        return map;
    }
}
